﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DingTalkAgent.Model;
using System.Reflection;
using Discuz.Common;
using System.Data;

namespace DingTalkAgent.Web.Controllers
{
    /// <summary>
    /// 用户平台平台端Controller基类 
    /// 可将公共数据或企业账户数据
    /// 
    /// 约定：（用户平台，对角色进行按用户模块权限划分。【其中通讯录为公众模块】）
    /// 为方便应该权限过滤，开发者为每个应用模块创建Controller，且保证同一应用不出现两Controller
    /// </summary>
    public class BaseController : Controller
    {
        /// <summary>
        /// 企业管理平台，登录者账户信息
        /// </summary>
        protected _view_account _view_account;
        //会话状态获取
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            requestContext.HttpContext.Session["User"] = new _view_account() { userid= "manager5443", corpId= "ding4e928dfcc1b3c5e835c2f4657eb6378f", corpSecret= "-MfosVsjkwfj-thDZrOev-vfNWVyGTh-mzuqcEJCmuAo-3XkB6Lp3-382wLKvRx6" };
            if (requestContext.HttpContext.Session["User"] != null)
            {

                _view_account = (_view_account)requestContext.HttpContext.Session["User"];
                //权限判断
                if (!AuthorizeCore(requestContext))
                {
                    requestContext.HttpContext.Response.Write("你无权操作");
                    requestContext.HttpContext.Response.End();
                    return;
                }

            }
            else
            {
                if (requestContext.HttpContext.Request.IsAjaxRequest())
                {
                    requestContext.HttpContext.Response.Write("CS00");
                    requestContext.HttpContext.Response.End();
                    return;
                }
                else
                {
                    requestContext.HttpContext.Response.Redirect("~/Account/LogOn");
                    return;
                }
            }
            ViewBag.skinCode = "default";
            base.Initialize(requestContext);
        }

        /// <summary>
        /// 权限判断业务逻辑
        /// </summary>
        /// <param name="filterContext"></param>
        /// <param name="isViewPage">是否为连接页</param>
        /// <returns></returns>
        protected virtual bool AuthorizeCore(System.Web.Routing.RequestContext filterContext)
        {
            return true;
            /*
            if (filterContext.HttpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }
            var controllerName = filterContext.RouteData.Values["controller"].ToString().ToLower();
            var actionName = filterContext.RouteData.Values["action"].ToString().ToLower();
            if (_view_account.roleID == "1")//
            {
                return true;
            }
            else
            {
                //通讯录读取和home用共用字段
                string commonstr = "home,member,organization,orgcustom";
                if (commonstr.Contains(controllerName))
                {

                    //公用中的特别权限
                    if (_view_account.Controllers.ToLower().Contains("member"))
                    {
                        ViewBag.memberPower = true;
                    }

                    //可以把通讯录的操作的action在这里控制下

                    return true;
                }
                else
                {
                    if (_view_account.Controllers.ToLower().Contains(controllerName))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }

            }
            */

        }

        public T Parse<T>(HttpRequestBase request, string key, T def = default(T))
        {
            T result = def;
            string str = string.Empty;
            try
            {
                str = request[key];
            }
            catch (Exception ex)
            {
                //logger.ErrorFormat("{0}，参数{1}={2}", ex.Message.ToString(), key, str);
            }
            if (string.IsNullOrWhiteSpace(str))
            {
                return result;
            }
            else
            {
                Type type = typeof(T);
                MethodInfo method = type.GetMethod("TryParse", new Type[] { typeof(String), typeof(T).MakeByRefType() });
                switch (type.ToString())
                {
                    case "System.Single":
                    case "System.Double":
                    case "System.Decimal":
                    case "System.Int32":
                    case "System.Int64":
                    case "System.DateTime":
                    case "System.Boolean":
                        object[] param = new object[2];
                        param[0] = str;
                        object item = method.Invoke(str, param);
                        if ((bool)item)
                        {
                            result = (T)param[1];
                        }
                        break;
                    default:
                        method = type.GetMethod("ToString", new Type[] { });
                        result = (T)method.Invoke(str, null);
                        break;
                }

                return result;
            }
        }

        public T Parse<T>(object obj, T def = default(T))
        {
            if (obj == null)
            {
                return def;
            }
            else
            {
                string str = obj.ToString();
                T result = def;
                Type type = typeof(T);
                MethodInfo method = type.GetMethod("TryParse", new Type[] { typeof(String), typeof(T).MakeByRefType() });
                switch (type.ToString())
                {
                    case "System.Single":
                    case "System.Double":
                    case "System.Decimal":
                    case "System.Int32":
                    case "System.Int64":
                    case "System.DateTime":
                    case "System.Boolean":
                        object[] param = new object[2];
                        param[0] = str;
                        object item = method.Invoke(str, param);
                        if ((bool)item)
                        {
                            result = (T)param[1];
                        }
                        break;
                    default:
                        method = type.GetMethod("ToString", new Type[] { });
                        result = (T)method.Invoke(str, null);
                        break;
                }

                return result;
            }
        }
                    /// <summary>
                    /// NPOI.dll方法导出Excel
                    /// </summary>
                    /// <param name="table">datatable</param>
                    /// <param name="fileName">文件名称</param>
                    /// <param name="strHeaderText">表头文本</param>
                    /// <returns></returns>
        [NonAction]
        protected FileContentResult ExportExcelBase(DataTable table, string fileName, string strHeaderText = null)
        {
            string dt = DateTime.Now.ToString("yyyyMMddHHmmss");
            string headerName = string.IsNullOrEmpty(fileName) ? dt : fileName;
            if (string.IsNullOrEmpty(fileName))
            {
                fileName = dt + ".xls";
            }
            else
            {
                fileName = fileName + "-" + dt + ".xls";
            }

            //ie 需要编码
            if (string.Compare(Request.Browser.Browser, "IE", true) == 0 || string.Compare(Request.Browser.Browser, "InternetExplorer", true) == 0)
            {
                fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
            }
            ExcelOp export = new ExcelOp();
            //var export = Common.ExeclExport.ExcelExportManage.Instance
            return File(export.ExportExcelFromDataTable(table, headerName).GetBuffer(),
                "application/vnd.ms-excel", fileName);
        }
    }
}